<?php
/**
 * Created by PhpStorm.
 * User: zhugeng
 * Date: 2019/7/15
 * Time: 16:05
 */

namespace app\api\controller;

use app\common\service\companyIndustry\tsinghua\TsinghuaEmissionService;
use app\common\service\ControlEmissionService;
use app\common\service\ControlService;
use app\common\service\EmissionService;
use app\common\service\FormulaService;
use think\Db;
use think\Request;
use think\facade\Config;
use app\common\service\FlugGasService;

class ControlSix extends BaseController
{

    /**
     * 处理接口异常
     * @param $plan_number
     * @param $type
     * @param $control_mode_id
     * @return array|bool
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getEmssion($plan_number, $type, $control_mode_id)
    {
        //step4:获取企业的减排前和方案值的排放量（主要获取目标排放量）
        $control = new ControlService();
        $emission_control = new ControlEmissionService();
        $endDay = 'yesterday';
        $days = 7;
        $unit = 'kg';
        try {
            $tsinghuaPlanName = $control->getConfirmTsinghuaPlanByPlanNumber($plan_number); //预案名称
            $lastEmission = $emission_control->getTsinghuaCompanyEmission($type, $control_mode_id, $plan_number, $tsinghuaPlanName, $unit);
            return $lastEmission;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 处理排放量异常
     * @param $plan_number
     * @param $type
     * @param $object_name
     * @return array|bool
     */
    public function getEmissionAll($plan_number, $type, $object_name)
    {
        $emission_control = new ControlEmissionService();
        try {
            $emission_all = $emission_control->getReductionEmission($plan_number, $type, $object_name);//排口排放量
            return $emission_all;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 精准管控-六
     * zhugeng 2019-07-15
     */
    public function companyIndustryMonitor()
    {
        $param = $this->request->param();
        if (empty($param['type']) || empty($param['control_mode_id']) || empty($param['plan_number']) || empty($param['region_id'])) {
            $this->error('参数错误');
        }
        $flug = new FlugGasService();
        $emission_control = new ControlEmissionService();
        //根据预案编号查询方案
        $object_sql = 'select * from control_plan_from_tsinghua_plan where plan_number = ? and confirm_scheme = 1';
        $object_info = Db::query($object_sql, array($param['plan_number']));
        if (!empty($object_info)) {
            $object_name = $object_info[0]['name'];
        } else {
            $object_name = '方案1';//默认方案1
        }
        //根据预案编号查询预案名称和管控开始时间
        $plan_sql = 'select plan_name,control_start_time,control_end_time from control_plan_name where plan_number = ?';
        $planNameInfo = Db::query($plan_sql, array($param['plan_number']));
        if (!empty($planNameInfo)) {
            $end_date = date('Y-m-d', strtotime('-2 day', strtotime($planNameInfo[0]['control_start_time'])));
            $start_date = date('Y-m-d', strtotime('-6 day', strtotime($end_date)));
        }

        //企业列表
        $limit = $flug->page($param['page'], 5);
        $sql = 'select type,is_realtime,plan_number,company_id,drain_id,drain_name,tracking_type from control_setting_list where type = ? and plan_number = ? and control_status = 0 and region_id = ? and tracking_type = ? order by company_id asc limit ?,?';
        $company_list = Db::query($sql, array($param['type'], $param['plan_number'], $param['region_id'], $param['control_mode_id'], $limit, 5));
        if (!empty($company_list)) {
            foreach ($company_list as $k => $v) {
                //根据公司id查询公司名
                $company_sql = 'select name,short_name from basic_company where id = ?';
                $companyInfo = Db::query($company_sql, array($v['company_id']));
                if (!empty($companyInfo)) {
                    $company_list[$k]['company_name'] = $companyInfo[0]['name'];
                }

                //获取减排前排口排放量(模拟企业和实时企业)
                $emissions = $emission_control->getSingleDrainEmissionsHourAvg($v['drain_id'], $param['plan_number']);
                if (!empty($emissions)) {
                    if ($param['type'] == 'SO2') {
                        $emissions_hour = $emissions['so2_emissions'];
                    } else {
                        $emissions_hour = $emissions['nox_emissions'];
                    }
                }
                //运行浓度减排前值
                $concentration_before = round($flug->beforeConcentration($start_date, $end_date, $v['company_id'], $v['drain_id'], $param['type'], $v['is_realtime'], $emissions_hour), 3);
                $company_list[$k]['concentration_before'] = $concentration_before;
                //运行效率减排前值
                $company_list[$k]['efficiency_before'] = round($flug->getCompanyFacilityOperatingEfficiency($v['drain_id'], $param['type'], $end_date, 7, $v['is_realtime'], $emissions_hour), 3);
                //获取清华方案排放量(模拟企业和实时企业)
                $emission_drain = $flug->getQingHuaEmissionDrainDayAvg($param['plan_number'], $param['control_mode_id'], $object_name, $v['company_id'], $v['drain_id'], $param['type'], $v['is_realtime']);
                if (!empty($emission_drain)) {
                    $qinghua_hour_avg = $emission_drain;
                } else {
                    $qinghua_hour_avg = 0;
                }
                //运行浓度方案值
                $company_list[$k]['concentration_project'] = round($flug->beforeProjectValue($planNameInfo[0]['control_start_time'], $planNameInfo[0]['control_end_time'], $v['company_id'], $v['drain_id'], $param['type'], $v['is_realtime'], $qinghua_hour_avg), 3);
                //运行效率方案值
                $company_list[$k]['efficiency_project'] = round($flug->getCompanyFacilityOperatingiDscharge($planNameInfo[0]['control_start_time'], $planNameInfo[0]['control_end_time'], $v['drain_id'], $param['type'], $v['company_id'], $v['is_realtime'], $qinghua_hour_avg), 3);
                //运行浓度当前值平均值
                $company_list[$k]['concentration_avg'] = round($flug->realtimeMonitorConcentrationNowHour($planNameInfo[0]['control_start_time'], $planNameInfo[0]['control_end_time'], $v['company_id'], $v['drain_id'], $param['type'], $v['is_realtime'], $param['plan_number'], $object_name), 3);
                //运行效率当前值平均值
                $company_list[$k]['efficiency_avg'] = round($flug->realtimeMonitorEfficiencyNowHour($planNameInfo[0]['control_start_time'], $planNameInfo[0]['control_end_time'], $v['company_id'], $v['drain_id'], $param['type'], $v['is_realtime'], $param['plan_number'], $object_name), 3);

                $list = $emission_control->getSingleDrainEmissionCompletionRate($v['drain_id'], $param['plan_number'], $object_name, $param['type']);
                if (!empty($list)) {
                    $company_list[$k]['objective_emission'] = round($list['target_emission'] / 1000000, 3);//目标排放量
                    $company_list[$k]['fish_emission'] = round($list['archive_emission'] / 1000000, 3); //已完成排放量
                    $company_list[$k]['completion_rate_of_emission_reduction'] = $list['rate_emission'];//减排前完成率
                }
            }
        }
        $sql_all = 'select type,is_realtime,plan_number,company_id,drain_id,drain_name,tracking_type from control_setting_list where type = ? and plan_number = ? and control_status = 0 and region_id = ? and tracking_type = ? order by company_id asc';
        $list_all = Db::query($sql_all, array($param['type'], $param['plan_number'], $param['region_id'], $param['control_mode_id']));
        $this->success_self('成功', $company_list, count($list_all));
    }

    /**
     * 精准管控-六
     * zhugeng 2019-07-15
     */
    public function companyIndustryMonitor1()
    {
        $param = $this->request->param();
        if (empty($param['type']) || empty($param['control_mode_id']) || empty($param['plan_number']) || empty($param['region_id'])) {
            $this->error('参数错误');
        }
        $sql_all = 'select * from control_step_six where plan_number = ? and type = ? and plan_id = ?';
        $list_all = Db::query($sql_all, array($param['plan_number'], $param['type'], $param['plan_id']));
        $sql = 'select * from control_step_six where plan_number = ? and type = ? and plan_id = ? order by company_id asc limit ?,5';
        $list = Db::query($sql, array($param['plan_number'], $param['type'], $param['plan_id'], $param['page']));
        $this->success_self('成功', $list, count($list_all));
    }

    //定时任务接口（管控第六步右侧企业列表）
    public function getCompanyListInfo()
    {
//        $result = Db::query('truncate control_step_six');//清空数据表
        $flug = new FlugGasService();
        $formula = new FormulaService();
        $control = new ControlService();
        $emission_control = new ControlEmissionService();

        $planList = [
            1 => '方案1',
            2 => '方案2',
            3 => '方案3'
        ];
        $planNumber = db::query('select * from control_plan_name order by id desc limit 0,1')[0];
        if (empty($planNumber)) die('今天没有预案!');
        $completeDays = $control->getPlanNumberDays($planNumber['plan_number']);
        $type = [
            'NO2',
            'SO2'
        ];
        $end_date = date('Y-m-d', strtotime('-2 day', strtotime($planNumber['control_start_time'])));
        $start_date = date('Y-m-d', strtotime('-6 day', strtotime($end_date)));
        for ($i = 0; $i < 2; $i++) {
            //企业列表
            $sql = 'select type,is_realtime,plan_number,company_id,drain_id,drain_name,tracking_type,name as company_name from control_setting_list join basic_company on basic_company.id = control_setting_list.company_id where type = ? and plan_number = ? and control_status = 0 and control_setting_list.region_id = ? and tracking_type = ?';
            $company_list = Db::query($sql, array($type[$i], $planNumber['plan_number'], 53, 1));
            for ($planId = 1; $planId < 4; $planId++) {
//                $completeEndDay = $control->getPlanNumberEndDay($planNumber['plan_number']);
//                $lastEmission = $this->getEmssion($planNumber['plan_number'], $type[$i], 1);
                $lastEmission = $emission_control->getTsinghuaCompanyEmission($type[$i], 1, $planNumber['plan_number'], $planList[$planId],  'kg');

                //获取所有排口排放量
                $emission_all = $this->getEmissionAll($planNumber['plan_number'], $type[$i], $planList[$planId]);
                if (!empty($company_list)) {
                    foreach ($company_list as $k => $v) {
                        $company_list[$k]['plan_id'] = $planId;
                        //根据公司id查询公司名
//                        $company_sql = 'select name,short_name from basic_company where id = ?';
//                        $companyInfo = Db::query($company_sql, array($v['company_id']));
//                        if (!empty($companyInfo)) {
//                            $company_list[$k]['company_name'] = $companyInfo[0]['name'];
//                        }

                        //获取减排前排口排放量
                        $emissions = 1;
                        if ($emission_all != 0) {
                            foreach ($emission_all as $k1 => $v1) {
                                if ($v['drain_id'] == $v1['drain_id']) {
                                    if ($v1['plan_emissions'] != 0) {
                                        $emissions = $v1['before_emissions'];
                                    }
                                }
                            }
                        }

                        //运行浓度减排前值
                        $concentration_before = round($flug->beforeConcentration($start_date, $end_date, $v['company_id'], $v['drain_id'], $type[$i], $v['is_realtime'], $emissions), 3);
                        $company_list[$k]['concentration_before'] = $concentration_before;
                        //运行效率减排前值
                        $company_list[$k]['efficiency_before'] = round($flug->getCompanyFacilityOperatingEfficiency($v['drain_id'], $type[$i], $end_date, 7, $v['is_realtime'], $emissions), 3);
                        //获取清华方案排放量
                        $qinghua_hour_avg = 1;
                        if ($emission_all != 0) {
                            foreach ($emission_all as $k1 => $v1) {
                                if ($v['drain_id'] == $v1['drain_id']) {
                                    if ($v1['plan_emissions'] != 0) {
                                        $qinghua_hour_avg = $v1['plan_emissions'];
                                    }
                                }
                            }
                        }
                        //运行浓度方案值
                        $company_list[$k]['concentration_project'] = round($flug->beforeProjectValue($planNumber['control_start_time'], $planNumber['control_end_time'], $v['company_id'], $v['drain_id'], $type[$i], $v['is_realtime'], $qinghua_hour_avg), 3);
                        //运行效率方案值
                        $company_list[$k]['efficiency_project'] = round($flug->getCompanyFacilityOperatingiDscharge($planNumber['control_start_time'], $planNumber['control_end_time'], $v['drain_id'], $type[$i], $v['company_id'], $v['is_realtime'], $qinghua_hour_avg), 3);
                        //运行浓度当前值平均值
                        $company_list[$k]['concentration_avg'] = round($flug->realtimeMonitorConcentrationNowHour($planNumber['control_start_time'], $planNumber['control_end_time'], $v['company_id'], $v['drain_id'], $type[$i], $v['is_realtime'], $planNumber['plan_number'], $planList[$planId]), 3);
                        //运行效率当前值平均值
                        $company_list[$k]['efficiency_avg'] = round($flug->realtimeMonitorEfficiencyNowHour($planNumber['control_start_time'], $planNumber['control_end_time'], $v['company_id'], $v['drain_id'], $type[$i], $v['is_realtime'], $planNumber['plan_number'], $planList[$planId]), 3);

                        if ($lastEmission == 0) continue;

                        foreach ($lastEmission as $k1 => $v1) {
                            if ($v['company_id'] != $v1['company_id'] || $v['drain_id'] != $v1['drain_id']) continue;

                            $company_list[$k]['objective_emission'] = $v1['target_emissions'];//目标排放量
                            $drainEmission = $flug->getSingleCompanyDrainEmissionMinToHourAvg((int)$v1['company_id'], $planNumber['control_end_time'], $completeDays, 'kg');
                            //已完成排放量
                            $company_list[$k]['fish_emission'] = '';
                            //减排前完成率
                            $company_list[$k]['completion_rate_of_emission_reduction'] = '';
                            if ($drainEmission != false) {
                                foreach ($drainEmission as $k2 => $v2) {
                                    if ((int)$v['drain_id'] == (int)$v2['drain_id']) {
                                        if ($type[$i] == 'NO2') {
                                            $company_list[$k]['fish_emission'] = (int)$v2['company_id'] == 1 ? $v2['nox_emissions_supplement'] : $v2['nox_emissions']; //已完成排放量
                                        }
                                        if ($type[$i] == 'SO2') {
                                            $company_list[$k]['fish_emission'] = (int)$v2['company_id'] == 1 ? $v2['so2_emissions_supplement'] : $v2['so2_emissions']; //已完成排放量
                                        }
                                        //减排前完成率
                                        $company_list[$k]['completion_rate_of_emission_reduction'] = $formula->completionRateOfEmissionReduction($company_list[$k]['fish_emission'], $lastEmission[$k]['target_emissions']);
                                    }
                                }
                            }
                        }
                    }
                }
                db::name('control_step_six')->insertAll($company_list);
            }
        }
    }

    /**
     * 减排前实际值趋势图
     */
    public function concentrationEfficiencyRealtime()
    {
        $param = $this->request->param();
//        $param['type'] = 'SO2';
//        $param['control_mode_id'] = 1;
//        $param['plan_number'] = 'CZ2019-07-27 001号';
//        $param['region_id'] = 53;
//        $param['company_id'] = 1;
//        $param['drain_id'] = 1;
//        $param['before_type'] = 2;
//        $param['is_realtime'] = 1;
        if (empty($param['type']) || empty($param['control_mode_id']) || empty($param['plan_number']) || empty($param['region_id']) || empty($param['drain_id']) || empty($param['company_id']) || empty($param['before_type'])) {
            $this->error('参数错误');
        }
        $PDOManager = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $plan_sql = 'select control_start_time from control_plan_name where plan_number = ?';
        $planNameInfo = Db::query($plan_sql, array($param['plan_number']));
        if (!empty($planNameInfo)) {
            $end_date = date('Y-m-d', strtotime('-2 day', strtotime($planNameInfo[0]['control_start_time'])));
            $start_date = date('Y-m-d', strtotime('-6 day', strtotime($end_date)));
        }
        if ($param['type'] == 'SO2') {
            $emission_colum = 'so2_emissions';
            $colum = 'operating_efficiency_so2 as efficiency,emissions_so2 as emissions';
            $field = 'emissions_so2 as emissions,operation_concentration_so2 as operation';
        } else {
            $emission_colum = 'nox_emissions';
            $colum = 'operating_efficiency_nox as efficiency,emissions_nox as emissions';
            $field = 'emissions_nox as emissions,operation_concentration_nox as operation';
        }
        $data = [];
        $emission = new ControlEmissionService();
        $smoke = new FlugGasService();
        //7天每小时排放量
        $emission_hour = $emission->getSingleDrainEmissionDetailsEveryHour($param['drain_id'], $param['plan_number'], 'before');
        //运行浓度实际值
        if ($param['before_type'] == 1) {
            if ($param['is_realtime'] == 1) {//实时企业
                //小时烟气量
                $smoke_hour = $smoke->monitorSulfurExitDrainSmokeHour($start_date, $end_date, $param['company_id'], $param['drain_id'], $param['type']);
                foreach ($smoke_hour as $k => $v) {
                    $data['date'][] = $v['_id']['day'] . ':00';
                    $data['data'][0][] = $emission_hour[$k][$emission_colum] / $v['s_emission'];
                }
            } else {//模拟企业
                $sql = 'select ' . $field . ' from company_industry_monitor_simulation_hour_avg where company_id = ? and drain_id = ?';
                $result = Db::query($sql, array($param['company_id'], $param['drain_id']));
                if (!empty($result)) {
                    $smoke_all = $result[0]['emissions'] / $result[0]['operation'];//小时烟气量
                } else {
                    $smoke_all = 1;//数据库没数据，烟气量返回1
                }
                foreach ($emission_hour as $k => $v) {
                    $data['date'][] = $v['publish_time'];
                    $data['data'][0][] = $v[$emission_colum] / $smoke_all;
                }
            }
        } else {//运行效率实际值
            $start_date = $start_date . ' 00:00:00';
            $end_date = $end_date . ' 23:59:59';
            if ($param['is_realtime'] == 1) {//实时企业
                if ($param['type'] == 'SO2') {
                    $table = 'company_industry_monitor_sulfur_minute';
                } else {
                    $table = 'company_industry_monitor_nitre_minute';
                }
                $sqlEmission = [
                    'aggregate' => $table,
                    'pipeline' => [
                        [
                            '$project' => [
                                '_id' => 1,
                                'drain_id' => 1,
                                'publish_time' => 1,
                                'operating_efficiency' => 1,
                                'emissions' => 1,
                                'day' => ['$substr' => ['$publish_time', 0, 13]]
                            ],
                        ],
                        [
                            '$match' => [
                                'publish_time' => ['$gte' => $start_date, '$lte' => $end_date],
                                'drain_id' => (int)$param['drain_id'],
                                'operating_efficiency' => ['$nin' => [0, 1]],
                            ]
                        ],
                        [
                            '$group' => [
                                '_id' => '$day',
                                'operating_efficiency' => [
                                    '$sum' => [ //求和
                                        '$divide' => [ //相除
                                            '$emissions',
                                            [
                                                '$subtract' => [ //相减
                                                    1, '$operating_efficiency'
                                                ]
                                            ]
                                        ]
                                    ]
                                ],
                            ]
                        ],
                        [
                            '$sort' => ['_id' => 1]
                        ]
                    ],
//                    'allowDiskUse' => true,
                    'cursor' => new \stdClass(),
                ];
                $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
                $sulfurDataObj = $PDOManager->executeCommand('huanxin', $commandEmission)->toArray();
//                $operatingEfficiency = json_decode(json_encode($sulfurDataObj[0], 320), true)['result'];
                $operatingEfficiency = mongoObjToArray($sulfurDataObj);
                //计算实时企业运行效率
                foreach ($operatingEfficiency as $k => $v) {
                    foreach ($emission_hour as $k1 => $v1) {
                        if ($v['_id'] . ':00' == $v1['publish_time']) {
                            $data['date'][$k] = $v['_id'] . ':00';
                            if (!is_nan($v['operating_efficiency'])) {
                                if ($v['operating_efficiency'] == 0) {
                                    $data['data'][0][$k] = 1;
                                } else {
                                    $data['data'][0][$k] = 1 - $v1[$emission_colum] / $v['operating_efficiency'];
                                }

                            } else {
                                $data['data'][0][$k] = '';
                            }
                        }
                    }

//                    else {
//                        $data['date'][$k] = $emission_hour[$k]['publish_time'];
//                        $data['data'][0][$k] = '';
//                    }

                }
            } else {//模拟企业
                //模拟企业  分钟排放量/(1-分钟效率)求和
                $sql = 'select ' . $colum . ' from company_industry_monitor_simulation_hour_avg where company_id = ? and drain_id = ?';
                $info = Db::query($sql, array($param['company_id'], $param['drain_id']));
                if (!empty($info)) {
                    $efficiency = $info[0]['efficiency'] / 60;//分钟效率平均值
                    $emissions = $info[0]['emissions'] / 60;//分钟排放量平均值
                } else {
                    $efficiency = 1;//上面返回0，0在下面作为分母不能计算（之前数据不对，先返回1，后面数据是对的）
                    $emissions = 1;
                }
                //计算模拟企业运行效率
                foreach ($emission_hour as $k => $v) {
                    $data['date'][$k] = $v['publish_time'];
                    $data['data'][0][$k] = 1 - ($v[$emission_colum] / ($emissions / (1 - $efficiency) * 60));
                }
            }
        }

        $this->success('成功', $data);
    }

    //测试当前值平均值
    public function aonitorAvg()
    {
        $param = $this->request->param();
        $abc = new FlugGasService();
        $list = $abc->realtimeMonitorSulfurDay($param['start_time'], $param['end_time'], $param['company_id'], $param['drain_id'], $param['con_type']);
        $this->success('成功', $list);
    }

    //测试烟气量
    public function aa()
    {
        $param = $this->request->param();
        if (empty($param['con_type']) || empty($param['control_mode_id']) || empty($param['plan_number']) || empty($param['qinghua_plan_name'])) {
            $this->error('参数错误');
        }
        $service = new FlugGasService();
        //脱硫运行浓度方案值
        $data = $service->monitorSulfurProjectValue($param['start_date'], $param['end_date'], $param['con_type'], $param['control_mode_id'], $param['plan_number'], $param['qinghua_plan_name']);

        $this->success('成功', $data);
    }

    //测试分钟填数
    public function getSmokeMinute()
    {
        $flug = new FlugGasService();
        $abc = $flug->smokeComplement('2019-07-11', '2019-07-12', 1, 1, 'NO2');
        return $abc;
    }


}